#include <event2/event.h>
#include <signal.h>
#include <string.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>

void read_cb(bufferevent *be, void *arg)
{
    //printf("r\r\n");
    char data[4092] = {0};
    memset(data, 0, sizeof(data));
    int len = bufferevent_read(be, data, sizeof(data)-1);

    if(len <= 0) return;

    printf("*********start\r\n%s\r\nend************\r\n",data);

}
void write_cb(bufferevent *be, void *arg)
{
    printf("w\r\n");

    char data[4092] = {0};
    memset(data, 0, sizeof(data));
    int len = bufferevent_read(be, data, sizeof(data)-1);

    if(len <= 0){
        printf("nonle\r\n");
    }

    printf("*********start\r\n%s\r\nend************\r\n",data);

}
void event_cb(bufferevent *be, short what, void *arg)
{
    if(what & BEV_EVENT_TIMEOUT){
        printf("bev timeout\r\n");
        //bufferevent_enable(be, EV_READ);
        bufferevent_free(be);
    }
    else {
        printf("other event\r\n");
    }
}
void listen_cb(evconnlistener *ev, evutil_socket_t s, sockaddr *sin, int slen, void *arg)
{
    //printf("enter listen_cb\r\n");

    event_base *base = (event_base*)arg;

    bufferevent *bev = bufferevent_socket_new(base, s, BEV_OPT_CLOSE_ON_FREE);

    //添加监控事件
    bufferevent_enable(bev, EV_READ|EV_WRITE);

    //水位
    //bufferevent_setwatermark(bev, EV_READ, 5, 10);
    //bufferevent_setwatermark(bev, EV_WRITE, 5, 0);

    //timeval t1 = {3, 0};
    //bufferevent_set_timeouts(bev, &t1, 0);

    //设置回调函数
    bufferevent_setcb(bev, read_cb, write_cb, event_cb, 0);

    

}
int main()
{
    if(signal(SIGPIPE, SIG_IGN) == SIG_ERR)
        return 1;

    event_base *base = event_base_new();

    /* create server */
    sockaddr_in sin;
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(9006);

    evconnlistener *ev = evconnlistener_new_bind(
        base,
        listen_cb,
        base,
        LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE,
        10,
        (sockaddr*)&sin,
        sizeof(sin)
    );

    if(ev==NULL){
        perror("error\r\n");
    }

    /* loop */
    event_base_dispatch(base);
    
    evconnlistener_free(ev);
    /* free */
    event_base_free(base);

    return 1;
}